package com.swind.fast.modules.app.space.rent.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

public class WordToHtmlUtil {

    private static final Logger logger = LoggerFactory.getLogger(WordToHtmlUtil.class);

    public static String docxToHtmlText(String filePath) throws Exception {
        File file = new File(filePath);
        String htmlStr = "";

        ByteArrayOutputStream htmlStream = new ByteArrayOutputStream();
        try {
            InputStream fileInputStream = new FileInputStream(file);

            // htmlStr = DocConvertUtil.getStr4Doc(in);

            // 将上传的文件传入Document转换
            XWPFDocument docxDocument = new XWPFDocument(fileInputStream);
            XHTMLOptions options = XHTMLOptions.create();

            XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance();
            xhtmlConverter.convert(docxDocument, htmlStream, options);

            docxDocument.createNumbering();
            // XHTMLConverter.getInstance().convert(docxDocument, htmlStream, options);
            htmlStr = htmlStream.toString();

            return htmlStr;
        } catch (Exception e) {
            logger.error("docxToHtmlText 解析异常", e);
            throw new RuntimeException(e);
        } finally {
            if (htmlStream != null) {
                htmlStream.close();
            }
        }
    }
}